<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="优惠券名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="form.name" placeholder="请输入优惠券名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="发放总数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalNum">
              <a-input-number v-model="form.totalNum" placeholder="请输入发放总数量" style="width: 100%"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="满(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="minPrice">
              <a-input-number v-model="form.minPrice" placeholder="请输入满多少" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="减(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subPrice">
              <a-input-number v-model="form.subPrice" :max="form.minPrice" placeholder="请输入减多少" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="优惠券类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="scopeType">
              <a-select v-model="form.scopeType">
                <a-select-option :value="1">
                  {{ shopType == 1 ? '平台通用' : '店铺通用' }}
                </a-select-option>
                <a-select-option v-if="shopType==1" :value="2">
                  指定品类
                </a-select-option>
                <a-select-option :value="3">
                  指定商品
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24" v-if="form.scopeType==2">
            <a-form-model-item label="选择类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryIds">
              <tip-cate-tree-select v-model="form.categoryIds" :type="'service'" :multiple="true" :placeholder="'请选择类目'"
                                    style="width: 100%">
              </tip-cate-tree-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24" v-if="form.scopeType==3">
            <a-form-model-item label="选择商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="itemCodes">
              <a-button @click="goodSelect">选择商品</a-button>
              <a-table ref="table" size="small" bordered rowKey="id" :columns="columns" :dataSource="form.gmsGoodList"
                       class="j-table-force-nowrap">
                <template slot="imgSlot" slot-scope="text">
                  <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                  <img v-else :src="text" height="40px" alt=""
                       style="max-width:80px;font-size: 12px;font-style: italic;"/>
                </template>
                <span slot="action" slot-scope="text, record,index">
                  <a @click="deleteItem(index)">删除</a>
                </span>
              </a-table>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="优惠券有效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expireType">
              <a-select :disabled="form.status==2" v-model="form.expireType" style="width: 100%"
                        placeholder="请选择优惠券有效时间">
                <a-select-option :key="1" :value="1">按领取时间</a-select-option>
                <a-select-option :key="2" :value="2">按指定时间</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="form.expireType==1">
            <a-form-model-item label="有效有效期，单位为天" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expireDay">
              <a-input-number :disabled="form.status==2" v-model="form.expireDay" placeholder="请输入有效有效期，单位为天"
                              style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="form.expireType==2">
            <a-form-model-item label="有效期开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startTime">
              <a-date-picker :disabled="form.status==2" v-model="form.startTime" :disabled-date="disabledStartDate"
                             placeholder="请选择有效期开始时间"
                             style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="form.expireType==2">
            <a-form-model-item label="有效期结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endTime">
              <a-date-picker :disabled="form.status==2" v-model="form.endTime" :disabled-date="disabledEndDate"
                             placeholder="请选择有效期结束时间"
                             style="width: 100%"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="限领张数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userNum">
              <a-input-number v-model="form.userNum" placeholder="请输入限领张数" style="width: 100%"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="允许在领券中心领取" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isJoin">
              <a-select v-model="form.isJoin" style="width: 100%">
                <a-select-option :key="1" :value="1">允许</a-select-option>
                <a-select-option :key="0" :value="0">不允许</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="允许在商品详情中领取" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isItemDetail">
              <a-select v-model="form.isItemDetail" style="width: 100%">
                <a-select-option :key="1" :value="1">允许</a-select-option>
                <a-select-option :key="0" :value="0">不允许</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="使用说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rule">
              <a-input v-model="form.rule" placeholder="请输入使用说明"></a-input>
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
    <gms-good-ref ref="modalGoodsSet" :selectionType="'checkbox'" @ok="modalGoodsOk"/>
  </a-spin>
</template>
<!--<template slot="rate" slot-scope="text,record">
  <div v-if="record.isCommission == 1">
    {{ text }}
  </div>
  <div v-else>
    {{ text }}
  </div>
</template>-->
<script>
import Vue from 'vue'
import {SHOP_TYPE, ORG_CODE} from "@/store/mutation-types"
import {httpAction, getAction} from '@/api/manage'
import pick from 'lodash.pick'
import {validateDuplicateValue} from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from "@/components/dict/JDictSelectTag"
import TipCateTreeSelect from '@/components/gospel/TipCateTreeSelect'
import GmsGoodRef from '@/views/gospel/mallBase/good/modules/GmsGoodRef'

export default {
  name: 'MmsCouponForm',
  components: {
    JFormContainer,
    JDate,
    JDictSelectTag,
    TipCateTreeSelect,
    GmsGoodRef
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {

    const validateSub = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入减免金额'))
      } else if (this.form.minPrice - 0 <= value - 0) {
        callback(new Error('减免金额不能大于等于“满”金额'))
      } else {
        callback()
      }
    }
    var validateStartTime = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择开始时间'))
      } else if (this.form.endTime && (this.form.startTime > this.form.endTime)) {
        callback(new Error('开始时间不得晚于结束时间'))
      } else {
        callback()
      }
    }
    var validateEndTime = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择结束时间'))
      } else if (this.form.startTime && (this.form.startTime > this.form.endTime)) {
        callback(new Error('开始时间不得晚于结束时间'))
      } else {
        callback()
      }
    }
    return {
      //当前用户店铺类型1:平台，2：自营，3：店铺，4：供应商
      shopType: Vue.ls.get(SHOP_TYPE),
      //当前用户部门code
      orgCode: Vue.ls.get(ORG_CODE),
      itemList: [],
      columns: [
        {
          title: '图片',
          align: "center",
          dataIndex: 'imgUrl',
          scopedSlots: {customRender: "imgSlot"}
        },
        {
          title: '名称',
          align: "center",
          dataIndex: 'title'
        },
        {
          title: '货号',
          align: "center",
          dataIndex: 'code'
        },
        {
          title: '价格',
          align: "center",
          dataIndex: 'price'
        },
        {
          title: '库存',
          align: "center",
          dataIndex: 'stock'
        },
        {
          title: '总销量',
          align: "center",
          dataIndex: 'dealNum'
        },
        {
          title: '分销比例',
          align: "right",
          dataIndex: {customRender: "rate"}
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {customRender: 'action'}
        }
      ],
      form: {
        name: '',
        remark: '',
        imgUrl: '',
        discountType: 0,
        minPrice: '',
        subPrice: '',
        discount: '',
        expireType: 1,
        expireDay: '',
        startTime: '',
        endTime: '',
        totalNum: '',
        receivedNum: '',
        userNum: '',
        isJoin: 1,
        isShare: '',
        isItemDetail: 1,
        sort: '',
        scopeType: '',
        isIntegral: '',
        integral: '',
        price: '',
        integralCouponNum: '',
        rule: '',
        status: 0,
        delFlag: '',
        createTime: '',
        updateTime: '',
        categoryIds: '',
        itemCodes: [],
        leftNum: '',
        useNum: '',
        expireNum: '',
        gmsGoodList: [],
        smsCategoryList: []
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      confirmLoading: false,
      rules: {
        name: [
          {required: true, message: '请输入优惠券名称!'},
        ],
        totalNum: [
          {required: true, message: '请输入发放总数量!'},
        ],
        minPrice: [
          {required: true, message: '请输入满!'},
        ],
        subPrice: [
          {required: true, message: '请输入减!'},
        ],
        scopeType: [
          {required: true, message: '请选择适用范围', trigger: 'change'}
        ],
        categoryIds: [
          {required: true, message: '请选择分类', trigger: 'change'}
        ],
        itemCodes: [
          {required: true, message: '请选择商品', trigger: 'change'}
        ],
        expireType: [
          {required: true, message: '请选择有效时间', trigger: 'change'}
        ],
        expireDay: [
          {required: true, message: '请输入有效有效期(正整数)', pattern: /^[+]?\d+$/, trigger: 'blur'}
        ],
        startTime: [
          {required: true, validator: validateStartTime, trigger: 'change'}
        ],
        endTime: [
          {required: true, validator: validateEndTime, trigger: 'change'}
        ],
        userNum: [
          {required: true, message: '请输入限领张数', trigger: 'blur'}
        ]
      },
      url: {
        add: "/mallPlus/mmsCoupon/add",
        edit: "/mallPlus/mmsCoupon/edit",
        queryById: "/mallPlus/mmsCoupon/queryById"
      }
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  created() {

  },
  methods: {
    disabledStartDate(startValue) {
      const endValue = this.form.endTime

      if (!startValue) {
        return false
      } else if (endValue) {
        return startValue.valueOf() >= endValue.valueOf() || startValue.valueOf() <= Date.now() - 86400000
      } else {
        return startValue.valueOf() <= Date.now() - 86400000
      }

    },
    disabledEndDate(endValue) {
      const startValue = this.form.startTime
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    modalGoodsOk(rows, keys) {
      const self = this
      this.form['itemCodes'] = []
      for (let i = 0; i < rows.length; i++) {
        this.form.itemCodes.push(rows[i].id)
      }
      this.form.gmsGoodList = rows

    },
    goodSelect() {
      let self = this
      self.$refs.modalGoodsSet.visible = true
      self.$refs.modalGoodsSet.checkedKeys = []
      self.$refs.modalGoodsSet.checkedRows = this.itemList
      for (let i = 0; i < this.itemList.length; i++) {
        self.$refs.modalGoodsSet.checkedKeys.push(this.itemList[i].itemCode)
      }
      self.$refs.modalGoodsSet.open(1)
    },

    add() {
      this.confirmLoading = false
      this.edit({
        shopId: '',
        name: '',
        remark: '',
        imgUrl: '',
        discountType: 0,
        minPrice: '',
        subPrice: '',
        discount: '',
        expireType: 1,
        expireDay: '',
        startTime: '',
        endTime: '',
        totalNum: '',
        receivedNum: '',
        userNum: '',
        isJoin: 1,
        isShare: '',
        isItemDetail: 1,
        sort: '',
        scopeType: '',
        isIntegral: '',
        integral: '',
        price: '',
        integralCouponNum: '',
        rule: '',
        status: 0,
        delFlag: '',
        createTime: '',
        updateTime: '',
        categoryIds: "",
        itemCodes: [],
        leftNum: '',
        useNum: '',
        expireNum: '',
        gmsGoodList: [],
        smsCategoryList: []

      })
    },
    edit(record) {
      this.confirmLoading = false
      if (record.id) {
        this.loadDetail(record.id)
      } else {
        this.form = Object.assign({}, record)
      }

      this.visible = true
    },
    loadDetail(id) {
      getAction(this.url.queryById, {id: id}).then((res) => {
        if (res.success) {
          this.form = res.result
        }
      })
    },
    deleteItem(index) {
      this.form.gmsGoodList.splice(index, 1)
      this.form.itemCodes.splice(index, 1)
    },
    submitForm() {
      const that = this
      if (that.confirmLoading) {
        return
      }
      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.form.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign({}, this.form)
          console.log("表单提交数据", formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).catch(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    popupCallback(row) {
      this.form = row
    },
  }
}
</script>
